package cn.amossun.starter.web.data.security.controller;

import cn.amossun.starter.common.enums.DesensitizedType;
import cn.amossun.starter.common.util.Page;
import cn.amossun.starter.web.data.security.IDataSecurityConfig;
import cn.amossun.starter.web.data.security.entity.DataSecurityConfigDTO;
import cn.amossun.starter.web.data.security.entity.Query;
import cn.amossun.starter.redis.cache.exception.RedisCacheConfigException;
import cn.amossun.starter.redis.cache.exception.RedisRelatedException;
import cn.amossun.starter.web.data.security.entity.Result;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Amos.Sun
 * @DateTime: 2020/07/07 19:58
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/security/config")
@ConditionalOnBean(IDataSecurityConfig.class)
public class DataSecurityConfigController {

	public final IDataSecurityConfig dataSecurityConfig;

	@GetMapping("/dynamic/redis")
	public Result<List<String>> getDynamicRedis() {
		return new Result(dataSecurityConfig.getDynamicRedis());
	}

	@GetMapping("/dynamic/desensitizedType")
	public Result<List<DesensitizedType>> getDesensitizedType() {
		return new Result(Arrays.stream(DesensitizedType.values()).collect(Collectors.toList()));
	}

	@GetMapping("/page")
	public Result<Page> getConfigs(DataSecurityConfigDTO param) throws Exception {
		return new Result(dataSecurityConfig.getOriginConfigs(param.getServiceName(), param.getCurrent(), param.getSize(), param.getTableName()));
	}

	@PostMapping("/save")
	public Result<Boolean> save(@RequestBody DataSecurityConfigDTO param) throws Exception {
		return new Result(dataSecurityConfig.save(param));
	}

	@PostMapping("/update")
	public Result<Boolean> update(@RequestBody DataSecurityConfigDTO param) throws Exception {
		return new Result(dataSecurityConfig.update(param));
	}

	@PostMapping("/remove")
	public Result<Boolean> remove(@RequestBody DataSecurityConfigDTO param) throws Exception {
		return new Result(dataSecurityConfig.remove(param));
	}

	@PostMapping("/rollback")
	public Result<Boolean> rollback(@RequestBody Query query) throws RedisCacheConfigException, RedisRelatedException {
		return new Result(dataSecurityConfig.rollback(query.getUserId(), query.getServiceName(), query.getVersion()));
	}

}
